package com.tubemostwanted.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tubemostwanted.entity.Tube;
import com.tubemostwanted.model.CategoryModel;
import com.tubemostwanted.model.TubeModel;

public class TubeDetailController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		String[] splitted = request.getRequestURI().split("/");
		String id = null;
		if (splitted.length == 4) {
			id = splitted[2];
		} else {
			System.out.println("Error path.");
			response.sendRedirect("/home");
		}
		try {
			System.out.println("Detail id : " + id);
			Tube detail = TubeModel.getByTubeId(id);
			if (detail != null) {
				long count = detail.getViewCount();
				count += 1;
				detail.setViewCount(count);
				TubeModel.update(detail);
				TubeModel.closePM();				
				request.setAttribute("detail", detail);
				request.setAttribute("categories", CategoryModel.all());
				request.setAttribute("url", request.getRequestURL());
				request.getRequestDispatcher("/tube_detail.jsp").forward(
						request, response);
			} else {
				System.out.println("Video is not exits.");
				request.getRequestDispatcher("/error.jsp").forward(request,
						response);
			}
		} catch (Exception e) {
			System.out.println("Exception.");
			e.printStackTrace();
			request.getRequestDispatcher("/error.jsp").forward(request,
					response);
		}
	}
}
